package top.itpath.admin.permission;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import top.itpath.admin.RequirePermission;
import top.itpath.admin.dto.UserInfo;
import top.itpath.common.exp.ForbiddenException;
import top.itpath.common.util.UserUtil;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * 申请角色权限检查
 *
 * @author zhaomengru
 * @time 2023/10/11 - 21:52
 */
@Aspect
@Component
public class RequirePermissionCheck {

    @Pointcut("@annotation(top.itpath.admin.RequirePermission)")
    public void checkRolePoint() {
    }

    @Before("checkRolePoint()")
    public void checkRole(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        RequirePermission annotation = method.getAnnotation(RequirePermission.class);
        String value = annotation.value();
        UserInfo currentUser = UserUtil.getCurrentUser();
        Set<String> permissions = currentUser.getPermissions();
        if (!permissions.contains(value)) {
            throw new ForbiddenException();
        }
    }
}
